package com.moose.operator.web.service.impl.poetry;

import com.moose.operator.common.QueryWrapper;
import com.moose.operator.model.entity.PoetryItemDetail;
import com.moose.operator.web.service.PoetryItemDetailService;
import java.util.List;
import javax.annotation.Resource;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author taohua
 */
@Service
public class PoetryItemDetailServiceImpl implements PoetryItemDetailService {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override public PoetryItemDetail getDetailByPoetryId(Integer poetryId) {
    Query query = QueryWrapper.buildQuery();
    Criteria criteria = Criteria.where("poetry_id").is(poetryId);
    query.addCriteria(criteria);
    PoetryItemDetail poetryItemDetail = mongoTemplate.findOne(query, PoetryItemDetail.class);

    Aggregation aggregation =
        Aggregation.newAggregation(
            Aggregation.match(Criteria.where("id").is(poetryId)),
            Aggregation.project("body")
        );

    AggregationResults<Document> aggregate =
        mongoTemplate.aggregate(aggregation, "poetry_item", Document.class);
    List<Document> mappedResults = aggregate.getMappedResults();
    if (mappedResults.size() > 0) {
      String body = mappedResults.get(0).getString("body");
      if (null != body && null != poetryItemDetail) {
        poetryItemDetail.setBody(body);
      }
    }
    return poetryItemDetail;
  }
}
